import axios from "axios";
import router from "@/router";

const request = axios.create({
    baseURL: '/',
    timeout: 30000,
})

// 请求拦截器
request.interceptors.request.use(function (config) {
    return config;
}, function (error) {
    return Promise.reject(error);
});

// 响应拦截器
request.interceptors.response.use(function (response) {
    return response.data;
}, function (error) {
    return Promise.reject(error);
});

export default function ajax(config) {
    const { url = '', method = 'get', data = {}, headers = {} } = config

    
    switch (method.toUpperCase()) {
        
        case 'GET':
            return request.get(url, { params: data })

        case 'POST':
            if (headers['content-type'] == 'application/x-www-form-urlencoded') {
                const obj = new URLSearchParams()
                for (const key in data) {
                    obj.append(key, data[key])
                }
                return request.post(url, obj, { headers })
            }

            if (headers['content-type'] == 'multipart/form-data') {
                const obj = new FormData()
                for (const key in data) {
                    obj.append(key, data[key])
                }
                return request.post(url, obj, { headers })
            }

            return request.post(url, data)
        case 'DELETE':
            return request.delete(url, { data })
        case 'PUT':
            return request.put(url, data)
        case 'PATCH':
            return request.patch(url, data)
        default:
            return request.request(config)
    }
}